package com.voicechat.firstmet.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.voicechat.firstmet.App;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PhotoAlbumBean;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.imcontrol.BroadcastManager;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.CircleImageView;
import com.voicechat.firstmet.view.LabelsView;
import com.voicechat.firstmet.view.RatingBarView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: CallEndActivity
 * @Description: 通话结束页面
 * @Author: ljp
 * @CreateDate: 2018/9/7 17:10
 * @Version: 1.0
 */
public class CallEndActivity extends BaseActivity {
    @BindView(R.id.rating_bar)
    RatingBarView ratingBar;
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.image_icon)
    CircleImageView imageIcon;
    @BindView(R.id.image_isanchor)
    ImageView imageIsanchor;
    @BindView(R.id.tv_nike_name)
    TextView tvNikeName;
    @BindView(R.id.image_sex)
    ImageView imageSex;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.linear_sex_age)
    LinearLayout linearSexAge;
    @BindView(R.id.image_vip)
    ImageView imageVip;
    @BindView(R.id.tv_voice_time)
    TextView tvVoiceTime;
    @BindView(R.id.tv_voice_gold)
    TextView tvVoiceGold;
    @BindView(R.id.tv_state)
    TextView tvState;
    @BindView(R.id.tv_remark)
    TextView tvRemark;
    @BindView(R.id.largeLabe_history)
    LabelsView largeLabeHistory;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    private String TAG = "CallEndActivity";
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String token;
    private String deviceInfo;
    private MySelfInfoBean.ObjectBean objectBean;
    private String voiceId;
    private int star;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_call_end;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
       // objectBean = getIntent().getParcelableExtra("mySelfInfoBean");
        voiceId = getIntent().getStringExtra("voiceId");
        initHttpData();
        initHttp();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //自己挂断
        BroadcastManager.getInstance(activity).addAction("2015", new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // toast_MakeText("2008");
                initHttpData();
                initHttp();
            }
        });
    }

    @Override
    protected void onDestroy() {
        BroadcastManager.getInstance(context).destroy("2015");
        super.onDestroy();
    }

    /**
     * @method
     * @description 请求数据
     * @date: 2018/12/13 11:23
     * @author: ljp
     * @return
     */
    private void initHttpData() {
        MeInfoService.voiceEndData(token, deviceInfo, mySeleInfo.getId(), voiceId).subscribe(mySelfInfoBean -> {
            //Log.i(TAG, "voiceEndData: ---getCode-----"+mySelfInfoBean.getCode());
            if (mySelfInfoBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
               // Log.i(TAG, "initView: ------通话时长----getDuration----"+mySelfInfoBean.getObject().toString());
                objectBean = mySelfInfoBean.getObject();
                initView();
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
            Log.i(TAG, "voiceEndData: -------" + throwable.toString());
        });

    }
    /**
    * @method
    * @description 请求语聊标签
    * @date: 2018/12/13 11:23
    * @author: ljp
    * @return
    */
    private void initHttp() {
        MeInfoService.voiceAppraise(token,deviceInfo).subscribe(photoAlbumBean -> {
            if(photoAlbumBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
               // List<PhotoAlbumBean.ListBean> list = photoAlbumBean.getPage().getList();
                 List<PhotoAlbumBean.PageBean.ListBean> list = photoAlbumBean.getPage().getList();
                largeLabeHistory.setLabels(list, new LabelsView.LabelTextProvider<PhotoAlbumBean.PageBean.ListBean>() {
                    @Override
                    public CharSequence getLabelText(TextView label, int position,PhotoAlbumBean.PageBean.ListBean data) {
                        return data.getTagName();
                    }
                });
            }
        },throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
        });

    }

    private void initView() {
        tvVoiceGold.setText("消耗金币："+objectBean.getGold()/10 );
        tvVoiceTime.setText("通话时长："+ Utils.getFormatHMS(objectBean.getDuration() * 1000));
        //Log.i(TAG, "initView: ------通话时长--------"+Utils.getFormatHMS(objectBean.getDuration() * 1000));
        tvNikeName.setText(objectBean.getNickName());
        GlideLoadUtils.getInstance().glideLoad(App.getContext(), OssConfig.OSS_HTTP + objectBean.getAvatarUrl(), imageIcon);
        if (objectBean.getGender() == 1) {//性别  1男2女
            linearSexAge.setBackgroundResource(R.mipmap.sex_blue);
            imageSex.setImageResource(R.mipmap.boy);
        } else {
            linearSexAge.setBackgroundResource(R.mipmap.sex_red);
            imageSex.setImageResource(R.mipmap.girl);
        }
        if (!TextUtils.isEmpty(objectBean.getvType())) {
            if (objectBean.getvType().equals("0")) {// 会员等级 0非会员 1月会员 2年会员
                imageVip.setVisibility(View.GONE);
            } else if (objectBean.getvType().equals("1")) {
                imageVip.setVisibility(View.VISIBLE);
                imageVip.setImageResource(R.mipmap.vip_month);
            } else if (objectBean.getvType().equals("2")) {
                imageVip.setVisibility(View.VISIBLE);
                imageVip.setImageResource(R.mipmap.vip_year);
            }
        }
        if (objectBean.getType() == 2) {//1普通用户2主播
            imageIsanchor.setVisibility(View.VISIBLE);
        } else {
            imageIsanchor.setVisibility(View.GONE);
        }
        //判断是否关注此用户
        if (objectBean.getStatus() == 0) {//关注状态  0未关注 1已关注 2互相关注
            tvState.setText("关注");
            tvState.setBackgroundResource(R.drawable.login_btn);
        } else if (objectBean.getStatus() == 1) {
            tvState.setText("已关注");
            tvState.setBackgroundResource(R.drawable.login_btn_2);
        } else if (objectBean.getStatus() == 2) {
            tvState.setText("互相关注");
            tvState.setBackgroundResource(R.drawable.login_btn_2);
        }

        largeLabeHistory.setMaxSelect(3);
        ratingBar.setStar(5,false);
        tvRemark.setText("非常满意");
        ratingBar.setOnRatingListener(new RatingBarView.OnRatingListener() {
            @Override
            public void onRating(Object bindObject, int RatingScore) {
                star = RatingScore;
                switch (RatingScore){//非常差 差 一般 满意 非常满意
                    case 1:
                        tvRemark.setText("非常差");
                        break;
                    case 2:
                        tvRemark.setText("差");
                        break;
                    case 3:
                        tvRemark.setText("一般");
                        break;
                    case 4:
                        tvRemark.setText("满意");
                        break;
                    case 5:
                        tvRemark.setText("非常满意");
                        break;
                }
            }
        });
        largeLabeHistory.setOnLabelClickListener(new LabelsView.OnLabelClickListener() {
            @Override
            public void onLabelClick(TextView label, Object data, int position) {

            }
        });
        tvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<PhotoAlbumBean.PageBean.ListBean> selectLabelDatas = largeLabeHistory.getSelectLabelDatas();
                StringBuffer sb = new StringBuffer();
                for (int i = 0;i< selectLabelDatas.size();i++ ){
                    sb.append(selectLabelDatas.get(i).getTagName()+",");
                }
                saveVoiceData(sb);

            }
        });

        linearBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvState.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvState.setEnabled(false);
                setHttpLike();
            }
        });
    }
    /**
    * @method
    * @description 提交评价
    * @date: 2018/12/13 18:55
    * @author: ljp
    * @return
    */
    private void saveVoiceData(StringBuffer sb) {
        if(star == 0){
            star = 5;
        }
        StringBuffer buffer = null;
        if(sb.length() != 0){
            buffer = sb.deleteCharAt(sb.length() - 1);
        }else {
            buffer = sb.append("");
        }
        MeInfoService.saveVoiceData(token,deviceInfo,voiceId,star+"",buffer.toString()).subscribe(result -> {
            Log.i(TAG, "saveVoiceData: ---------"+result.toString());
            if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                toast_MakeText("评价成功");
            }
        },throwable -> {

        });
        finish();

    }

    /**
     * @return
     * @method
     * @description 关注取消关注
     * @date: 2018/10/24 11:56
     * @author: ljp
     */
    private void setHttpLike() {
        MeInfoService.likeAndUnLike(token, deviceInfo, mySeleInfo.getId(), objectBean.getId()).subscribe(result -> {
            Log.i(TAG, "setHttpLike: --------" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                if (objectBean.getStatus() == 0) {//关注状态  0未关注 1已关注 2互相关注
                    tvState.setText("已关注");
                    tvState.setBackgroundResource(R.drawable.login_btn_2);
                    objectBean.setStatus(1);
                } else if (objectBean.getStatus() == 1) {
                    tvState.setText("关注");
                    tvState.setBackgroundResource(R.drawable.login_btn);
                    objectBean.setStatus(0);
                } else if (objectBean.getStatus() == 2) {
                    tvState.setText("关注");
                    tvState.setBackgroundResource(R.drawable.login_btn);
                    objectBean.setStatus(0);
                }
                //toast_MakeText(result.getMsg());
            } else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                removeAllActivity();
                startActivity(new Intent(activity,LoginActivity.class));
            }else {
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
            Log.i(TAG, "setHttpLike: ------" + throwable.toString());

        });
        tvState.setEnabled(true);

    }
}
